
// Celsus.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "afxwinappex.h"
#include "Celsus.h"
#include "MainFrm.h"

#include "CelsusDoc.h"
#include "CelsusView.h"
#include "DlgInformation.h"
#include "Splash.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CCelsusApp

BEGIN_MESSAGE_MAP(CCelsusApp, CWinApp)
	ON_COMMAND(ID_APP_ABOUT, &CCelsusApp::OnAppAbout)
	ON_COMMAND(ID_HELP_INFORMATION, &CCelsusApp::OnHelpInformation)
	ON_COMMAND(ID_VIEW_WEBSERVER, &CCelsusApp::OnViewWebserver)
END_MESSAGE_MAP()


// CCelsusApp construction

CCelsusApp::CCelsusApp()
{
	m_bSplash = TRUE;
}

// The one and only CCelsusApp object

CCelsusApp theApp;
CAppConfig appConfig;


// CCelsusApp initialization

BOOL CCelsusApp::InitInstance()
{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	//// show splash screen
	//CSplash *pSplash = new CSplash( IDB_BITMAP_SPLASH, CSplash::KillOnClick, &pSplash );

	// Get commandline
	GetCommandLine();
	// Get path for INI
	if( !GetINIPath() )
		return FALSE;
	
	// read configuration
	appConfig.ReadConfig();

	// add fonts folder
	AddFontsFolder();

	// Initialize OLE libraries
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}
	
	//AfxEnableControlContainer();
	CCustomOccManager *pMgr = new CCustomOccManager;
	// Create an IDispatch class for extending the Dynamic HTML Object Model
	m_pDispOM = new CImpIDispatch;
	AfxEnableControlContainer(pMgr);
	
	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("TeamSoftware Solutions"));
	LoadStdProfileSettings(0);  // Load standard INI file options (including MRU)

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CCelsusDoc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CCelsusView));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);


	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	// The one and only window has been initialized, so show and update it
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();
	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand

	//// close splash screen
	//if( pSplash )
	//	pSplash->Kill();

	return TRUE;
}

int CCelsusApp::ExitInstance()
{
	// delete IDispatch
	delete m_pDispOM;

	return CWinApp::ExitInstance();
}

void CCelsusApp::GetCommandLine(void)
{
	for (INT i = 1; i < __argc; i++)
	{
		LPCTSTR pszParam = __targv[i];
		BOOL bFlag = FALSE;
		BOOL bLast = ((i + 1) == __argc);
		if (pszParam[0] == '-' || pszParam[0] == '/')
		{
			// remove flag specifier
			bFlag = TRUE;
			++pszParam;
		}
		if (bFlag)
		{
			CString csFlag = pszParam;
			csFlag.MakeLower();
			if( csFlag.Left( 3 ) == _T("ini") )
				appConfig.SetINIPath( csFlag.Right( csFlag.GetLength() - 4 ));
		}
	}
}

BOOL CCelsusApp::GetINIPath(void)
{
	CString szPath;
	szPath = appConfig.GetINIPath();
    if( appConfig.GetINIPath().IsEmpty() )
	{
		CString szAppPath;
		INT nIndex = 0;
		TCHAR cBuffer[MAX_PATH];

		memset(cBuffer, NULL, MAX_PATH);
		GetModuleFileName(NULL, cBuffer, MAX_PATH);
		
		szAppPath = cBuffer;
		nIndex = szAppPath.ReverseFind('\\') + 1;
		appConfig.SetINIPath( szAppPath.Left( nIndex ) + _T("Celsus.ini") );
	}
	else if( szPath.Find('\\') == -1 )
	{
		CString szAppPath;
		INT nIndex = 0;
		TCHAR cBuffer[MAX_PATH];

		memset(cBuffer, NULL, MAX_PATH);
		GetModuleFileName(NULL, cBuffer, MAX_PATH);
		
		szAppPath = cBuffer;
		nIndex = szAppPath.ReverseFind('\\') + 1;
		appConfig.SetINIPath( szAppPath.Left( nIndex ) + szPath );
	}

	// INI not found
	if( !PathFileExists( appConfig.GetINIPath() ))
	{
		CString csMessage;
		csMessage.Format( _T("ERROR:\n\nThe INI file %s was not found.\n\nCelsus will now exit."), appConfig.GetINIPath() );		
		AfxMessageBox( csMessage );
		return FALSE;
	}
	return TRUE;
}

BOOL CCelsusApp::AddFontsFolder(void)
{
	CString szPath;
	INT nIndex = 0;
	TCHAR cBuffer[MAX_PATH];
	memset(cBuffer, NULL, MAX_PATH);
	GetModuleFileName(NULL, cBuffer, MAX_PATH);
	szPath = cBuffer;
	nIndex = szPath.ReverseFind('\\') + 1;
	szPath = szPath.Left( nIndex ) + _T("fonts");

	// copy bar code fonts
	if( PathFileExists( szPath ))
	{
		CString szFontFile;
		WIN32_FIND_DATA FindFileData;
		HANDLE hFind;
		
		// Find the first file in the directory.
		hFind = FindFirstFile( szPath + _T("\\*.ttf"), &FindFileData);
		
		if (hFind == INVALID_HANDLE_VALUE) 
		{
			appConfig.ShowLastError( GetLastError() );
			return FALSE;
		} 
		else 
		{
			// add first
			szFontFile = FindFileData.cFileName;
			AddFontResource( szPath + _T("\\") + szFontFile );

			// add the other files in the directory.
			while( FindNextFile(hFind, &FindFileData ) != 0 )
			{
				szFontFile = FindFileData.cFileName;
				AddFontResource( szPath + _T("\\") + szFontFile );
			}
			FindClose( hFind );
			return TRUE;
		}
	}
	return FALSE;
}

// CCelsusApp message handlers

void CCelsusApp::OnHelpInformation()
{
	CDlgInformation dlgInfo;
	// set URL
	dlgInfo.m_szURL = appConfig.m_General.szInformationFile;
	dlgInfo.DoModal();
}

void CCelsusApp::OnViewWebserver()
{
	// open web server
	ShellExecute( NULL, _T("open"), appConfig.m_General.szRootFolder, NULL, NULL, SW_SHOWNORMAL );
}


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();
	virtual BOOL OnInitDialog();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
public:
	CString m_szVersion;
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
, m_szVersion(_T(""))
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_STATIC_VERSION, m_szVersion);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()

// App command to run the dialog
void CCelsusApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

BOOL CAboutDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// set version
	m_szVersion.LoadString( IDS_CELSUS_VERSION );

	// update data
	UpdateData( FALSE );

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
